package com.xiyuan.smartutils.client.http;

import com.xiyuan.smartutils.IoUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;

/**
 * HTTP/HTTPS GET访问类，把HttpURLConnection的流转化成ByteArrayInputStream，该类为非文本响应内容时使用
 *
 * @version v1.0.0 @author lgz 2017-9-21 新建与整理
 * @see HttpDownload 大文件下载，请使用HttpDownload替换，以防止内存使用过大
 */
public class HttpGetStream extends HttpClient {
    private ByteArrayOutputStream in;
    
    public HttpGetStream(String url) {
        super(url, _GET_);
    }
    
    /**
     * 重写获取HTTP结果
     */
    public HttpResult getResult() {
        return new HttpResult(responseStatus, responseText, in == null ? null : in.toByteArray());
    }
    
    /**
     * 获取输入流
     */
    public InputStream getInputStream() {
        return new ByteArrayInputStream(in.toByteArray());
    }
    
    /**
     * 获取字节数组
     */
    public byte[] getBytes() {
        return in.toByteArray();
    }
    
    @Override
    protected void doReadContent(HttpURLConnection conn) throws IOException {
        if (responseStatus == _302_FOUND_.getCode()) {//重定向
            responseText = conn.getHeaderField("Location");
            return;
        }
        
        if (responseStatus != _200_OK_.getCode()) {//错误
            responseText = getResponseError(conn);
            return;
        }
        
        //成功
        in = new ByteArrayOutputStream();
        try (InputStream input = conn.getInputStream()) {
            IoUtils.putBytes(input, in);
        }
        
        responseText = "调用成功";
    }
}
